package it.asvp.asvp_portal.data.dao.impl;

import it.asvp.asvp_portal.data.dao.EventDao;
import it.asvp.asvp_portal.data.entity.event.Event;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class EventDaoImpl implements EventDao {

	private static final Log log = LogFactory.getLog(EventDaoImpl.class);

	@Autowired
	private SessionFactory sessionFactory;

	public Long persist(Event transientInstance) {
		log.debug("persisting Event instance");
		Long id;
		try {
			id=(Long)sessionFactory.getCurrentSession().save(transientInstance);
			log.debug("persist successful");
		} catch (RuntimeException re) {
			log.error("persist failed", re);
			throw re;
		}
		return id;
	}

	public void delete(Event persistentInstance) {
		log.debug("deleting Event instance");
		try {
			sessionFactory.getCurrentSession().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public Event merge(Event detachedInstance) {
		log.debug("merging Event instance");
		try {
			Event result = (Event) sessionFactory.getCurrentSession().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public Event findById(java.lang.Long id) {
		log.debug("getting Event instance with id: " + id);
		
		Criteria cr=sessionFactory.getCurrentSession().createCriteria(Event.class);
		cr.add(Restrictions.eq("id", id));
		Event e = (Event)cr.uniqueResult();
		return e;
	}
	
	@SuppressWarnings("unchecked")
	public List<Event> findAll() {
		log.debug("getting all Event instances ");
		
		//ragruppato per tipo e in ordine crescente
		Criteria cr=sessionFactory.getCurrentSession().createCriteria(Event.class);
		List<Event> list = (List<Event>)cr.list();
		return list;
	}
	
	@SuppressWarnings("unchecked")
	public List<Event> findByPriority(boolean priority) {
		log.debug("getting all Event instance by priority: ");
		
		Criteria cr=sessionFactory.getCurrentSession().createCriteria(Event.class);
		cr.add(Restrictions.eq("priority", priority));
		List<Event> list= (List<Event>)cr.list();
		return list;
	}
}
